/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.RefundStatusEnum;
import com.yami.shop.bean.enums.RefundType;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.cp.comment.model.CollaborativePurchaseAddr;
import com.yami.shop.cp.comment.model.UserSubmitPerson;
import com.yami.shop.cp.comment.service.CollaborativePurchaseAddrService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseBasketService;
import com.yami.shop.cp.comment.service.UserSubmitPersonService;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/p/myOrder")
@Api(tags = "我的订单接口")
@AllArgsConstructor
public class MyOrderController {

    private final OrderService orderService;

    private final MapperFacade mapperFacade;

    private final UserAddrOrderService userAddrOrderService;

    private final ProductService productService;

    private final SkuService skuService;

    private final ShopConfig shopConfig;
    private final WxConfig wxConfig;
    private final DeliveryService deliveryService;
    private final MyOrderService myOrderService;

    private final ShopDetailService shopDetailService;

    private final OrderItemService orderItemService;
    private final DeliveryOrderService deliveryOrderService;
    private final OrderRefundService orderRefundService;
    private final CollaborativePurchaseAddrService collaborativePurchaseAddrService;
    private final UserSubmitPersonService userSubmitPersonService;


    /**
     * 订单详情信息接口
     */
    @GetMapping("/orderDetail")
    @ApiOperation(value = "订单详情信息", notes = "根据订单号获取订单详情信息")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<OrderShopDto> orderDetail(@RequestParam(value = "orderNumber", required = true) String orderNumber) {
        String userId = "";
        try {
            userId = SecurityUtils.getUser().getUserId();
        } catch (Exception e) {
            String mobile = SecurityUtils.getSubmitPerson().getMobile();
            UserSubmitPerson userSubmitPerson = userSubmitPersonService.getOne(new LambdaQueryWrapper<UserSubmitPerson>()
                    .eq(UserSubmitPerson::getMobile, mobile));
            userId = userSubmitPerson.getUserId();
        }
        OrderShopDto orderShopDto = new OrderShopDto();
        Order order = null;
        if (Objects.nonNull(userId)) {
            order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);
        } else {
            order = orderService.getOne(new LambdaQueryWrapper<Order>()
                    .eq(Order::getOrderNumber, orderNumber)
                    .eq(Order::getDvyType, 2)
                    .eq(Order::getDvyId, SecurityUtils.getUser().getStationId())
            );
        }
        ShopDetail shopDetail;
        if (Objects.equals(order.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            shopDetail = new ShopDetail();
            shopDetail.setShopName(Constant.PLATFORM_SHOP_NAME);
        } else {
            shopDetail = shopDetailService.getShopDetailByShopId(order.getShopId());
        }
        UserAddrDto userAddrDto = null;
        if (!Objects.equals(order.getDvyType(), DvyType.STATION.value())) {
            UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
            userAddrDto = mapperFacade.map(userAddrOrder, UserAddrDto.class);
        }
        if (Objects.isNull(userAddrDto) && Objects.nonNull(order.getCollaborativePurchaseId())) {
            CollaborativePurchaseAddr cpAddr = collaborativePurchaseAddrService.getOne(new LambdaQueryWrapper<CollaborativePurchaseAddr>()
                    .eq(CollaborativePurchaseAddr::getCollaborativePurchaseId, order.getCollaborativePurchaseId()));
            userAddrDto = new UserAddrDto();
            userAddrDto.setAddrId(cpAddr.getId());
            userAddrDto.setReceiver(cpAddr.getReceiver());
            userAddrDto.setProvince(cpAddr.getProvince());
            userAddrDto.setCity(cpAddr.getCity());
            userAddrDto.setArea(cpAddr.getArea());
            userAddrDto.setAddr(cpAddr.getAddress());
            userAddrDto.setMobile(cpAddr.getMobile());
            userAddrDto.setProvinceId(cpAddr.getProvinceId());
            userAddrDto.setCityId(cpAddr.getCityId());
            userAddrDto.setAreaId(cpAddr.getAreaId());
        }


        orderShopDto.setShopId(shopDetail.getShopId());
        orderShopDto.setDvyType(order.getDvyType());
        orderShopDto.setShopName(shopDetail.getShopName());
        orderShopDto.setActualTotal(order.getActualTotal());
        orderShopDto.setUserAddrDto(userAddrDto);
        orderShopDto.setPayType(order.getPayType());

        //如果存在用户等级免运费金额，说明是包邮的，此时运费金额等于免运费金额，否则默认是订单运费
        if (order.getFreeTransfee() != null && order.getFreeTransfee() > 0) {
            orderShopDto.setTransfee(order.getFreeTransfee());
        } else {
            orderShopDto.setTransfee(order.getFreightAmount());
        }
        orderShopDto.setFreeTransfee(order.getFreeTransfee());
//        Math.abs
        orderShopDto.setReduceAmount(Math.abs(order.getReduceAmount()));
        orderShopDto.setCreateTime(order.getCreateTime());
        orderShopDto.setRemarks(order.getRemarks());
        orderShopDto.setOrderType(order.getOrderType());
        orderShopDto.setStatus(order.getStatus());
        // 付款时间
        orderShopDto.setPayTime(order.getPayTime());
        // 发货时间
        orderShopDto.setDvyTime(order.getDvyTime());
        // 完成时间
        orderShopDto.setFianllyTime(order.getFinallyTime());
        // 取消时间
        orderShopDto.setCancelTime(order.getCancelTime());
        // 更新时间
        orderShopDto.setUpdateTime(order.getUpdateTime());


        refundOrderItemInfo(orderNumber, orderShopDto, order);
        return ResponseEntity.ok(orderShopDto);
    }

    private void refundOrderItemInfo(String orderNumber, OrderShopDto orderShopDto, Order order) {
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());

        //计算订单使用积分
        Integer score = 0;
        for (OrderItem orderItem : orderItems) {
            score += orderItem.getUseScore();
        }
        orderShopDto.setOrderScore(score);

        List<OrderItemDto> orderItemDtoList = mapperFacade.mapAsList(orderItems, OrderItemDto.class);

        List<OrderRefund> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());

        // 可以退款的状态，并在退款时间内
        if (order.getStatus() > OrderStatus.UNPAY.value() && order.getStatus() < OrderStatus.CLOSE.value() && orderRefundService.checkRefundDate(order)) {
            orderShopDto.setCanRefund(true);
            // 有没有正在退款中的订单
            if (CollectionUtil.isEmpty(orderRefunds)) {
                orderShopDto.setCanAllRefund(true);
            }
        }

        for (OrderRefund orderRefund : orderRefunds) {

            // 整单退款
            if (Objects.equals(RefundType.ALL.value(), orderRefund.getRefundType())) {
                orderShopDto.setCanRefund(false);
                // 统一的退款单号
                for (OrderItemDto orderItemDto : orderItemDtoList) {
                    orderItemDto.setRefundSn(orderRefund.getRefundSn());
                }
                break;
            }
            // 单项退款，每个单号都不一样
            for (OrderItemDto orderItemDto : orderItemDtoList) {
                if (Objects.equals(orderItemDto.getOrderItemId(), orderRefund.getOrderItemId())) {
                    orderItemDto.setRefundSn(orderRefund.getRefundSn());
                }
            }

        }

        orderShopDto.setOrderItemDtos(orderItemDtoList);
        double total = 0.0;
        Integer totalNum = 0;
        for (OrderItemDto orderItem : orderShopDto.getOrderItemDtos()) {
            total = Arith.add(total, orderItem.getProductTotalAmount());
            totalNum += orderItem.getProdCount();
        }
        orderShopDto.setTotal(total);
        orderShopDto.setTotalNum(totalNum);
    }


    /**
     * 订单列表接口
     */
    @GetMapping("/myOrder")
    @ApiOperation(value = "订单列表信息", notes = "根据订单状态获取订单列表信息，状态为0时获取所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败 7待成团", required = false, dataType = "Integer"),
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrder(@RequestParam(value = "status") Integer status, PageParam<MyOrderDto> page) throws WxErrorException {

        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByUserIdAndStatus(page, userId, status, I18nMessage.getDbLang());
        return ResponseEntity.ok(myOrderDtoIpage);
    }

    /**
     * 订单列表查询接口
     */
    @GetMapping("/myOrderSearch")
    @ApiOperation(value = "订单列表信息查询", notes = "根据订单编号或者订单中商品名称搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderName", value = "订单编号或者订单中商品名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "orderTimeStatus", value = "0全部订单 1最近七天 2最近三个月 3三个月之前 订单", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderType", value = "0全部订单 1拼团订单 2秒杀订单 3普通订单", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderNumber", value = "订单编号", required = false, dataType = "String")
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrderSearch(@RequestParam(value = "status") Integer status,
                                                           @RequestParam(value = "orderName") String orderName,
                                                           @RequestParam(value = "orderTimeStatus") Integer orderTimeStatus,
                                                           @RequestParam(value = "orderType") Integer orderType,
                                                           @RequestParam(value = "orderNumber") String orderNumber,
                                                           @RequestParam(value = "shopId", required = false) Long shopId,
                                                           PageParam<MyOrderDto> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByParams(page, userId, status, orderName, orderTimeStatus, orderType, orderNumber, I18nMessage.getDbLang(), shopId);
        return ResponseEntity.ok(myOrderDtoIpage);
    }

    /**
     * 获取订单项信息
     */
    @GetMapping("/getOrderItem")
    public ResponseEntity<OrderItem> getOrderItem(@RequestParam(value = "orderItemId") Long orderItemId) {
        String imgDomainName = shopConfig.getDomain().getResourcesDomainName();
        OrderItem orderItem = orderItemService.getById(orderItemId);
        orderItem.setPic(orderItem.getPic() != null ? imgDomainName + "/" + orderItem.getPic() : null);
        return ResponseEntity.ok(orderItem);
    }

    /**
     * 获取订单项信息
     */
    @GetMapping("/getOrderItems")
    public ResponseEntity<List<OrderItem>> getOrderItems(@RequestParam(value = "orderNumber") Long orderNumber) {
        String imgDomainName = shopConfig.getDomain().getResourcesDomainName();
        List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
        for (OrderItem orderItem : orderItems) {
            orderItem.setPic(orderItem.getPic() != null ? imgDomainName + "/" + orderItem.getPic() : null);
        }
        return ResponseEntity.ok(orderItems);
    }

    /**
     * 订单评价列表接口
     */
    @GetMapping("/myOrderComment")
    @ApiOperation(value = "订单评价列表接口", notes = "根据订单评价状态获取订单列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commStatus", value = "订单状态 0:待评价 1已评价", required = false, dataType = "Integer")
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrderComment(@RequestParam(value = "commStatus") Integer commStatus, PageParam<MyOrderDto> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.myOrderComment(page, userId, commStatus);
        return ResponseEntity.ok(myOrderDtoIpage);
    }

    /**
     * 订单项评价列表接口
     */
    @GetMapping("/myOrderItemsComment")
    @ApiOperation(value = "订单项评价列表接口", notes = "根据订单评价状态获取订单列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commStatus", value = "订单状态 0:待评价 1已评价", required = false, dataType = "Integer")
    })
    public ResponseEntity<IPage<MyOrderItemDto>> myOrderItemsComment(@RequestParam(value = "commStatus") Integer commStatus, PageParam<MyOrderItemDto> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderItemDto> myOrderDtoIpage = myOrderService.myOrderItemsComment(page, userId, commStatus);
        return ResponseEntity.ok(myOrderDtoIpage);
    }


    /**
     * 取消订单
     */
    @PutMapping("/cancel/{orderNumber}")
    @ApiOperation(value = "根据订单号取消订单", notes = "根据订单号取消订单")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<String> cancel(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();
        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);
        if (!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value())) {
            // 订单已支付，无法取消订单
            throw new YamiShopBindException("yami.order.status.change");
        }

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());
        order.setOrderItems(orderItems);
        // 取消订单
        orderService.cancelOrders(Collections.singletonList(order));
        // 清除缓存
        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            productService.removeProdCacheByProdId(orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(), orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(), orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }
        return ResponseEntity.ok().build();
    }


    /**
     * 确认收货
     */
    @PutMapping("/receipt/{orderNumber}")
    @ApiOperation(value = "根据订单号确认收货", notes = "根据订单号确认收货")
    public ResponseEntity<String> receipt(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();
        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);

        if (!Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value())) {
            // 订单未发货，无法确认收货
            throw new YamiShopBindException("yami.order.no.delivery");
        }
        if (Objects.equals(order.getRefundStatus(), RefundStatusEnum.APPLY.value())) {
            // 订单退款中，无法确认收货
            throw new YamiShopBindException("yami.order.receipt.refund");
        }
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());
        order.setOrderItems(orderItems);
        // 确认收货
        orderService.receiptOrder(Collections.singletonList(order));

        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            productService.removeProdCacheByProdId(orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(), orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(), orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderNumber}")
    @ApiOperation(value = "根据订单号删除订单", notes = "根据订单号删除订单")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<String> delete(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();

        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);

        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())) {
            // 订单未完成或未关闭，无法删除订单
            throw new YamiShopBindException("yami.order.no.success");
        }

        // 删除订单
        orderService.deleteOrders(Collections.singletonList(order));

        // 删除成功
        return ResponseEntity.ok(I18nMessage.getMessage("yami.delete.successfully"));
    }


//    /**
//     * 获取我的订单订单数量
//     */
//    @GetMapping("/orderCount")
//    @ApiOperation(value = "获取我的订单订单数量", notes = "获取我的订单订单数量")
//    public ResponseEntity<OrderCountData> getOrderCount() {
//        String userId = SecurityUtils.getUser().getUserId();
//        OrderCountData orderCountMap = orderService.getOrderCount(userId);
//        return ResponseEntity.ok(orderCountMap);
//    }


}
